
package gwtcomettest.atm.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.StatusCodeException;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import java.io.Serializable;
import java.util.List;
import com.greencat.gwt.comet.client.CometClient;
import com.greencat.gwt.comet.client.CometListener;
import com.greencat.gwt.comet.client.CometSerializer;

/**
 *
 * @author p.havelaar
 */
public class GWTTest implements EntryPoint {

    BroadcastAsync broadcast = GWT.create(Broadcast.class);
    PollAsync polling = GWT.create(Poll.class);

    @Override
    public void onModuleLoad() {

        Button button = new Button("Broadcast");
        button.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                sendMessage();
            }
        });
        
        Button pollButton = new Button("Poll");
        pollButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                polling.pollDelayed(5000, new AsyncCallback<Event>() {

                    @Override
                    public void onFailure(Throwable caught) {
                        GWT.log("Failed to poll", caught);
                    }

                    @Override
                    public void onSuccess(Event result) {
                        Info.display("Polling message received: " + result.getCode(), result.getData());
                    }
                });
            }
        });
        
        RootPanel.get("buttons").add(button);
        RootPanel.get("buttons").add(pollButton);

        final CometClient client = initialize();

        Button killbutton = new Button("Stop");
        killbutton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                client.stop();
            }
        });
        
        RootPanel.get("buttons").add(killbutton);
        
    }
    
    
    private static class MyCometListener implements CometListener {

        @Override
        public void onConnected(int heartbeat, int connectionID) {
            GWT.log("comet.connected [" +heartbeat+", "+connectionID+"]");
        }

        @Override
        public void onDisconnected() {
            GWT.log("comet.disconnected");
        }

        @Override
        public void onError(Throwable exception, boolean connected) {
            int statuscode =-1;
            if (exception instanceof StatusCodeException) {
                statuscode = ((StatusCodeException)exception).getStatusCode();
            }
            GWT.log("comet.error [connected=" + connected + "] ("+statuscode+")", exception);
        }

        @Override
        public void onHeartbeat() {
            GWT.log("comet.heartbeat ["+client.getConnectionID()+"]");
        }

        @Override
        public void onRefresh() {
            GWT.log("comet.refresh ["+client.getConnectionID()+"]");
        }

        @Override
        public void onMessage(List<? extends Serializable> messages) {
            StringBuilder result = new StringBuilder();
            for(Serializable obj : messages) {
                result.append(obj.toString()).append("<br/>");
            }
            GWT.log("comet.message ["+client.getConnectionID()+"] " + result.toString());
            Info.display("["+client.getConnectionID()+"] Received " + messages.size() + " messages", result.toString());
        }

        CometClient client;
    };

    public CometClient initialize() {

        MyCometListener cometListener = new MyCometListener();

        CometSerializer serializer = GWT.create(EventSerializer.class);
        // set a small length parameter to force refreshes
        // normally you should remove the length parameter
        CometClient client = new CometClient(GWT.getModuleBaseURL()+"gwtComet", serializer, cometListener);
        cometListener.client = client;
        client.start();
        return client;
    }

    static int count = 0;
    public void sendMessage() {
        broadcast.broadcastEvent(new Event(count++, "Button clicked!"), new AsyncCallback<Void>() {
            @Override
            public void onFailure(Throwable caught) {
                GWT.log("Failed to broadcast", caught);
            }

            @Override
            public void onSuccess(Void result) {
            }
        });
    }
}
